package com.example.demo.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.example.demo.service.AIService;
import kong.unirest.HttpResponse;
import kong.unirest.Unirest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AIServiceImpl implements AIService {

    @Value("${ai.api.key:默认API密钥}")
    private String apiKey;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String getAIResponse(String question) {
        try {
            HttpResponse<String> response = Unirest.post("https://api.siliconflow.cn/v1/chat/completions")
                    .header("Authorization", "Bearer " + apiKey)
                    .header("Content-Type", "application/json")
                    .body("{\n" +
                          "  \"model\": \"deepseek-ai/DeepSeek-R1-Distill-Qwen-32B\",\n" +
                          "  \"stream\": false,\n" +
                          "  \"max_tokens\": 625,\n" +
                          "  \"temperature\": 0.7,\n" +
                          "  \"top_p\": 0.7,\n" +
                          "  \"top_k\": 60,\n" +
                          "  \"frequency_penalty\": 1.0,\n" +
                          "  \"n\": 1,\n" +
                          "  \"messages\": [\n" +
                          "    {\n" +
                          "      \"role\": \"user\",\n" +
                          "      \"content\": \"" + question.replace("\"", "\\\"") + "\"\n" +
                          "    }\n" +
                          "  ]\n" +
                          "}")
                    .asString();

            if (response.isSuccess()) {
                JsonNode jsonResponse = objectMapper.readTree(response.getBody());
                return jsonResponse.path("choices").path(0).path("message").path("content").asText();
            } else {
                return "AI助手请求失败: " + response.getStatus() + " - " + response.getBody();
            }
        } catch (Exception e) {
            return "AI助手发生错误: " + e.getMessage();
        }
    }

    @Override
    public String[] getMultipleAIResponses(String question, int numberOfResponses) {
        try {
            HttpResponse<String> response = Unirest.post("https://api.siliconflow.cn/v1/chat/completions")
                    .header("Authorization", "Bearer " + apiKey)
                    .header("Content-Type", "application/json")
                    .body("{\n" +
                          "  \"model\": \"deepseek-ai/DeepSeek-R1-Distill-Qwen-32B\",\n" +
                          "  \"stream\": false,\n" +
                          "  \"max_tokens\": 625,\n" +
                          "  \"temperature\": 0.7,\n" +
                          "  \"top_p\": 0.7,\n" +
                          "  \"top_k\": 60,\n" +
                          "  \"frequency_penalty\": 1.0,\n" +
                          "  \"n\": " + Math.min(numberOfResponses, 10) + ",\n" +
                          "  \"messages\": [\n" +
                          "    {\n" +
                          "      \"role\": \"user\",\n" +
                          "      \"content\": \"" + question.replace("\"", "\\\"") + "\"\n" +
                          "    }\n" +
                          "  ]\n" +
                          "}")
                    .asString();

            if (response.isSuccess()) {
                JsonNode jsonResponse = objectMapper.readTree(response.getBody());
                JsonNode choices = jsonResponse.path("choices");
                List<String> responses = new ArrayList<>();

                for (int i = 0; i < choices.size(); i++) {
                    responses.add(choices.path(i).path("message").path("content").asText());
                }

                return responses.toArray(new String[0]);
            } else {
                return new String[]{"AI助手请求失败: " + response.getStatus() + " - " + response.getBody()};
            }
        } catch (Exception e) {
            return new String[]{"AI助手发生错误: " + e.getMessage()};
        }
    }
} 